using Newtonsoft.Json.Linq;


namespace Quicklogin.Server.Yidun
{
    public class Oneclick
    {
        public static string GetPhoneNumber(string accessToken,string token)
        {
            /** 产品密钥ID，产品标识 */
            String secretId = "9cb0ddac608c956cd09307117f12efbc";
            /** 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露 */
            String secretKey = "1e839d7da6b8f5f486ee74771ead07ff";
            /** 业务ID，易盾根据产品业务特点分配 */
            String businessId = "01e659b45a3040f297c0824267ea39d7";
            /** 一键登录在线检测接口地址 */
            String apiUrl = "https://ye.dun.163yun.com/v1/oneclick/check";

            Dictionary<string, string> parameters = new Dictionary<string, string>();
            long curr = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            string time = curr.ToString();

            // 1.设置公共参数
            parameters.Add("secretId", secretId);
            parameters.Add("businessId", businessId);
            parameters.Add("version", "v1");
            parameters.Add("timestamp", time);
            parameters.Add("nonce", Guid.NewGuid().ToString("N"));

            // 2.设置私有参数
            parameters.Add("accessToken", accessToken); // 运营商预取号获取到的token
            parameters.Add("token", token); // 易盾返回的token
            // accessToken, token都是一次性有效, 且2分钟后自动过期

            // 3.生成签名信息
            string signature = Utils.genSignature(secretKey, parameters);
            parameters.Add("signature", signature);

            // 4.发送HTTP请求
            HttpClient client = Utils.makeHttpClient();
            string result = Utils.doPost(client, apiUrl, parameters, 10000);
            if (result != null)
            {
                JObject ret = JObject.Parse(result);
                int code = ret.GetValue("code").ToObject<int>();
                string msg = ret.GetValue("msg").ToObject<string>();
                if (code == 200)
                {
                    JObject data = (JObject)ret.SelectToken("data");
                    string phone = data.GetValue("phone").ToObject<string>();
                    if (phone != null)
                    {
                        // 取号成功, 成功登录系统
                        return phone;
                    }
                    else
                    {
                        string resultCode =  data.GetValue("resultCode").ToObject<string>();
                        Console.WriteLine(string.Format("运营商返回码: resultCode={0}", resultCode));
                          // 降级走短信
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("ERROR: code={0}, msg={1}", code, msg));
                    // 降级走短信
                }
            }
            else
            {
                Console.WriteLine("Request failed!");
            }

            return string.Empty;
        }
    }
}